package top.xzxsrq.utils;

import cn.hutool.core.io.FileUtil;

import java.io.File;
import java.io.IOException;

/**
 * 所有的分隔符全部采用   /
 */
public abstract class PathUtils {
    public static boolean isChildPath(String childPath, String parentPath) {
        return getCanonicalPath(childPath).startsWith(getCanonicalPath(parentPath));
    }

    public static boolean isChildPath(File childPath, File parentPath) {
        try {
            return isChildPath(childPath.getCanonicalPath(), parentPath.getCanonicalPath());
        } catch (IOException e) {
            return false;
        }
    }

    public static String getCanonicalPath(String filePath) {
        return getCanonicalPath(new File(filePath));
    }

    public static String getCanonicalPath(File file) {
        String absolutePath = file.getAbsolutePath();
        // getCanonicalPath这玩意在window大小不敏感
//            String canonicalPath = file.getCanonicalPath();
        return PathUtils.pathStandardization(absolutePath);
    }

    public static String pathStandardization(String path) {
        boolean isStart = path.startsWith("./");
        String normalize = FileUtil.normalize(path);
        normalize = normalize
                // ./ 这种路径替换成/
                .replaceAll("\\./", "/");
        if (isStart) {
            return "./" + normalize;
        }
        return normalize;
    }

    /**
     * 路径拼接
     *
     * @param basePath
     * @param relativePath
     * @return
     */
    public static String pathResolve(String basePath, String relativePath) {
        if(relativePath == null) {
            relativePath = "/";
        }
        File file = new File(relativePath);
        if (file.isAbsolute()) {
            return pathStandardization(relativePath);
        }
        if (!basePath.endsWith("/") && !relativePath.startsWith("/")) {
            return pathStandardization(basePath + "/" + relativePath);
        }
        return pathStandardization(basePath + relativePath);
    }

    /**
     * 判断两个路径是否相等，直接判断是否指向同一个文件
     *
     * @param path1
     * @param path2
     * @return
     */
    public static boolean isEquals(String path1, String path2) {
        String canonicalPath = getCanonicalPath(path1);
        String canonicalPath1 = getCanonicalPath(path2);
        return canonicalPath1.equals(canonicalPath);
    }
}
